package com.cy.pj.common.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 缓存切面
 */
@Aspect
@Component
public class SysCacheAspect {
    // 缓存对象
    private Map<String, Object> cache = new ConcurrentHashMap<>();// 线程安全

    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
    public void doCache(){}// 切入点

    @Pointcut("@annotation(com.cy.pj.common.annotation.ClearCache)")
    public void doClearCache(){}

    // 成功执行后，清除缓存
    @AfterReturning("doClearCache()")
    public void doAfterReturning() {
        System.out.println("SysCacheAspect.clearCache 清除缓存");
        cache.clear();// 清除缓存
    }

    @Around("doCache()") // 环绕通知
    public Object around(ProceedingJoinPoint pj) throws Throwable{
        try{
            System.out.println("get data from cache");
            Object result = null;
            if(cache != null) {
                result = cache.get("deptKey");// 这里的key先用一个固定值，将来结合业务进行设计
                if(result != null) return result;
            }
            result = pj.proceed();
            System.out.println("put data to cache");
            cache.put("deptKey", result);
            return result;
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }
    }
}
